<?php

namespace App\Console\Commands;

use App\Common\Constant\Params;
use App\Models\Master;
use App\Models\MasterDetail;
use App\Models\MasterStatistic;
use App\Models\MasterWallet;
use App\Models\OldMaster;
use App\Models\Province;
use App\Services\IAreaService;
use App\Services\IMasterService;
use App\Services\IStorageService;
use DB;
use Illuminate\Console\Command;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Support\Collection;
use Log;

class importMaster extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'import:old-master {offset=0}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入师傅';

    private $exceptionHandler;
    private $masterService;
    private $storageService;
    private $areaService;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(ExceptionHandler $exceptionHandler,IMasterService $masterService,IStorageService $storageService,IAreaService $areaService)
    {
        parent::__construct();

        $this->exceptionHandler = $exceptionHandler;
        $this->masterService = $masterService;
        $this->storageService = $storageService;
        $this->areaService = $areaService;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $bar = $this->output->createProgressBar(OldMaster::count());
        $offset = $this->argument('offset');

        $areas = getAreas();
        $area_names = [];
        foreach ($areas as $area){
            $area_names[$area['n']] = $area;
        }

//        $model = OldMaster::first();
        
        OldMaster::orderBy('ma_id')->chunk(100, function ($masters) use (&$bar,&$area_names,&$offset){
            foreach ($masters as $model) {
                if ($bar->getProgress() < $offset){
                    $this->line("\tMaster [{$model->ma_userid}] skip");
                    $bar->advance();
                    continue;
                }
                if (Master::where('weixin_userid',$model->ma_userid)->count()){
                    $this->line("\tMaster [{$model->ma_userid}] exists");
                    $bar->advance();
                    continue;
                }

                DB::beginTransaction();
                try{
                    $ma_address = explode(',',$model->ma_address);
//                    $area_id = end($ma_address) ? Province::where('name',end($ma_address))->first()->id : 0;
                    $area_id = @$area_names[end($ma_address)]['i'] ? : 0;
                    $service_area_ids = Collection::make(explode(',',$model->ma_servicearea))->map(function($item,$key) use (&$area_names){
                        return @$area_names[$item]['i'];
//                        return @Province::where('name',$item)->first()->id;
                    });
                    $service_type = Collection::make(explode(',',$model->ma_servicetype))->map(function($item,$key){
                        return [
                            1=>Params::SERVICE_TYPE_DELIVERY,
                            2=>Params::SERVICE_TYPE_CARRY,
                            3=>Params::SERVICE_TYPE_INSTALL,
                            4=>Params::SERVICE_TYPE_REPAIR,
                        ][$item];
                    });
                    $master = Master::create([
                        'id'=>$model->ma_id,
                        'weixin_userid' => $model->ma_userid,
                        'phone' => $model->ma_phone,
                        'real_name' => $model->ma_truename,
                        'idcard' => $model->ma_idcard,
                        'area_id' => $area_id,
                        'area_text' => $this->areaService->getAreaCrumbById($area_id),
                        'service_area_ids' => array_filter($service_area_ids->toArray()),
                        'service_category' => Params::SERVICE_CATEGORY_FURNITURE,
                        'service_type' => array_filter($service_type->toArray()),
                        'idcard_front' => $model->ma_idcardfront ? ($this->storageService->saveUrl('http://www.lebangdaojia.com/upload/'.$model->ma_idcardfront) ? : '') : '',
                        'idcard_back' => $model->ma_idcardback ? ($this->storageService->saveUrl('http://www.lebangdaojia.com/upload/'.$model->ma_idcardback) ? : '') : '',
                        'idcard_hold' => $model->ma_photo ? ($this->storageService->saveUrl('http://www.lebangdaojia.com/upload/'.$model->ma_photo) ? : '') : '',
                        'status' => Params::USER_STATUS_NORMAL
                    ]);
                    if (!$master){
                        throw new \Exception('master create fail');
                    }
                    $ret = MasterDetail::create([
                        'master_id' => $master->id,
                        'car_num'=>$model->ma_havecarnum,
                        'extra_storage'=>$model->ma_havewarehouse,
                        'backup_phone'=>$model->ma_psphone,
                        'member_num'=>$model->ma_teamnum,
                    ]);
                    if (!$ret){
                        throw new \Exception('master detail create fail');
                    }
                    $ret = MasterWallet::create([
                        'master_id' => $master->id
                    ]);
                    if (!$ret){
                        throw new \Exception('master wallet create fail');
                    }
                    $ret = MasterStatistic::create([
                        'master_id' => $master->id,
                        'order_count'=>$model->ma_finishnum,
                    ]);
                    if (!$ret){
                        throw new \Exception('master statistic create fail');
                    }

                    DB::commit();
                    $this->info("\tMaster [{$model->ma_userid}] success");
                }catch (\Exception $e){
                    DB::rollBack();
                    $this->error("\tMaster [{$model->ma_userid}] fail\nerror: ".$e->getMessage()." in ".$e->getFile()."[".$e->getLine()."]\n");
                    Log::error("\tMaster [{$model->ma_userid}] fail\nerror: ".$e->getMessage()." in ".$e->getFile()."[".$e->getLine()."]\n");
                    $this->exceptionHandler->report($e);
                }

                $bar->advance();
            }
        });

        $bar->finish();

    }
}
